package com.leyou.order.interceptor;

import com.leyou.common.auth.pojo.AppInfo;
import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.constants.LyConstants;
import com.leyou.order.config.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 微服务鉴权拦截器
 */
@Component
public class AppTokenInterceptor implements HandlerInterceptor{
    @Autowired
    private JwtProperties jwtProps;

    /**
     * 返回值：
     *   true：放行
     *   false：拦截
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        //2.校验服务token是否合法
        Payload<AppInfo> payload = null;
        try {
            //1.从request取出服务token请求头
            String appToken = request.getHeader(LyConstants.APP_TOKEN_HEADER);
            payload = JwtUtils.getInfoFromToken(appToken, jwtProps.getPublicKey(), AppInfo.class);
        } catch (Exception e) {
            //拦截
            return false;
        }

        //3.从服务token取出合法服务列表
        AppInfo appInfo = payload.getInfo();
        List<String> targetList = appInfo.getTargetList();

        //4.判断当前服务是否在合法服务列表中
        if(!targetList.contains(jwtProps.getApp().getServiceName())){
            //拦截
            return false;
        }

        //放行
        return true;
    }
}
